package com.fjnu.dao.impl;

import com.fjnu.dao.TagDao;
import com.fjnu.domain.entity.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class TagDaoImpl implements TagDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int insert(Tag tag) {
        if (tag == null || tag.getName() == null || tag.getName().trim().isEmpty()) {
            return 0;
        }

        String sql = "INSERT INTO tb_tag(name, create_time, update_time) VALUES(?, NOW(), NOW())";
        return jdbcTemplate.update(sql, tag.getName());
    }

    @Override
    public int insertArticleTag(Integer articleId, Integer tagId) {
        if (articleId == null || tagId == null) {
            return 0;
        }
        String sql = "INSERT INTO tb_article_tag(article_id, tag_id) VALUES(?, ?)";
        return jdbcTemplate.update(sql, articleId, tagId);
    }

    @Override
    public int delete(Integer tagId) {
        if (tagId == null) {
            throw new IllegalArgumentException("标签ID不能为空");
        }
        String sql = "DELETE FROM tb_tag WHERE id = ?";
        return jdbcTemplate.update(sql, tagId);
    }

    @Override
    public List<Tag> selectAll() {
        String sql = "SELECT * FROM tb_tag ORDER BY create_time DESC";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Tag.class));
    }

    @Override
    public Tag selectById(Integer tagId) {
        if (tagId == null) {
            throw new IllegalArgumentException("标签ID不能为空");
        }
        String sql = "SELECT * FROM tb_tag WHERE id = ?";
        List<Tag> tags = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Tag.class), tagId);
        return tags.isEmpty() ? null : tags.get(0);
    }

    @Override
    public Tag selectByName(String name) {
        if (name == null || name.trim().isEmpty()) {
            throw new IllegalArgumentException("标签名称不能为空");
        }
        String sql = "SELECT * FROM tb_tag WHERE name = ?";
        List<Tag> tags = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Tag.class), name.trim());
        return tags.isEmpty() ? null : tags.get(0);
    }

    @Override
    public int deleteArticleTagByTagId(Integer tagId) {
        if (tagId == null) {
            throw new IllegalArgumentException("标签ID不能为空");
        }
        String sql = "DELETE FROM tb_article_tag WHERE tag_id = ?";
        return jdbcTemplate.update(sql, tagId);
    }
}